<?php

include FCPATH . 'application/controllers/backend/backend.php';

class Photo extends Backend{

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $this->load->model('album_model');
        $data = array(
            'albums' => $this->album_model->records()
        );
        $this->load_javascripts('backend_photo');
        $this->load_stylesheets('backend_photo');
        $this->rend('photo_index_view', $data);
    }

    public function find() {
        $this->load->model('photo_model');
        $id = intval($this->uri->segment(4));
        $data = $this->photo_model->find($id);
        if ($data) {
            $this->json_back('XT001', '', $data);
        } else {
            $this->json_back('XT002', '数据库错误');
        }
    }

    public function records() {
        $this->load->model('photo_model');
        $album = intval($this->input->get('album'));
        $page = intval($this->input->get('page'));
        $page_size = intval($this->input->get('pageSize'));
        $offset = ($page - 1) * $page_size;
        $conditions = array(
            array('album', $album)
        );
        $this->json_back('XT001', '', array(
            'total' => $this->photo_model->total($conditions),
            'records' => $this->photo_model->records($page_size, $offset, $conditions)
        ));
    }

    public function insert() {
        $this->load->model('photo_model');
        $date_string = date('Ymd', time());
        $label = trim($this->input->post('label'));
        $data = array(
            'album' => intval($this->input->post('album')),
            'description' => trim($this->input->post('description')),
            'creater' => intval($this->session->userdata('user_id')),
            'created_at' => date('Y-m-d H:i:s', time())
        );
        $config = array(
            'upload_path' => FCPATH . 'assets/uploads/' . $date_string . '/',
            'allowed_types' => 'gif|jpg|png|bmp',
            'max_size' => '2048',
            'max_width' => '1024',
            'max_height' => '1024',
            'encrypt_name' => true
        );

        if (!file_exists($config['upload_path'])) {
            mkdir($config['upload_path'], 0777);
        }

        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('photo')) {
            $this->upload_back('XT002', $this->upload->display_errors());
        } else {
            $upload_data = $this->upload->data();
        }

        
        $data['label'] = empty($label) ? preg_replace('/\.[^\.]*/','',$upload_data['orig_name'] ): $label;
        $data['file_name'] = $date_string . '/' . $upload_data['file_name'];

        //生成缩略图 需开启gd2库
        unset($config);
        $config['image_library'] = 'gd2';
        $config['source_image'] = $upload_data['full_path'];
        $config['new_image'] = $upload_data['file_path'];
        $config['create_thumb'] = true;
        $config['maintain_ratio'] = true;
        $config['width'] = 150;
        $config['height'] = 150;
        $this->load->library('image_lib', $config);
        $this->image_lib->resize();
 
        if ($this->photo_model->insert($data)) {
            $this->upload_back('XT001', '', $upload_data);
        } else {
            //图片上传成功 但是数据没有能插入数据库 提示错误，删除上传的文件
            @unlink($upload_data['full_path']);
            $this->upload_back('XT002', '由于数据错误导致图片上传失败');
        }
    }

    public function update() {
        $this->load->model('photo_model');
        $id = intval($this->input->post('id'));

        $data = array(
            'label' => trim($this->input->post('label'))
        );

        if ($this->photo_model->update($id, $data)) {
            $this->json_back('XT001');
        } else {
            $this->json_back('XT002', 'database error.');
        }
    }

    public function delete() {
        $this->load->model('photo_model');
        $ids = explode(',', trim($this->input->get('id')));

        if (empty($ids)) {
            $this->json_back('XT002', 'You have not select a picture.');
        }

        //删除图片文件
        $this->db->where_in('id', $ids);
        $query = $this->db->get('jd_photo');
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $photo) {
                $photo_path = FCPATH . 'assets/uploads/' . $photo->file_name;
                if (file_exists($photo_path)) {
                    @unlink($photo_path);
                }
                $photo_thumb_path = preg_replace("/\.(jpg|jpeg|png|bmp|gif)$/",'_thumb.\1',$photo_path);
                if (file_exists($photo_thumb_path)) {
                    @unlink($photo_thumb_path);
                }
                unset($photo, $photo_path,$photo_thumb_path);
            }
        }
        $query->free_result();

        //删除图片数据库记录
        if ($this->photo_model->delete_batch($ids)) {
            $this->json_back('XT001');
        } else {
            $this->json_back('XT002', 'database error.');
        }
    }
    
    public function cover(){
        $id = intval($this->uri->segment(4));
        
        $this->load->model(array('album_model','photo_model'));
        
        if(($photo = $this->photo_model->find($id))){
            if(($album = $this->album_model->find($photo->album))){
                if($this->album_model->update($album->id,array('cover'=>$id))){
                    $this->json_back('XT001','设置封面成功');
                }else{
                    $this->json_back('XT002', 'database error.');
                }
            }else{
                $this->json_back('XT002', '图片所属相册不存在',array('album'=>$album,'photo'=>$photo));
            }
        }else{
            $this->json_back('XT002', '图片不存在');
        }
    }
    
    public function order(){
	$id  = intval($this->input->post('id'));
	
	$order = intval($this->input->post('order'));
	
	$this->load->model('photo_model');
	
	//删除图片数据库记录
        if ($this->photo_model->order($id,$order)) {
            $this->json_back('XT001','排序成功');
        }
	
        $this->json_back('XT002', 'database error.');
    }

}
